
package com.bangcommunity.bbframe.test.hook;

import com.bangcommunity.bbframe.common.utils.io.NetUtil;
import com.bangcommunity.bbframe.common.utils.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import com.alibaba.dubbo.config.ProtocolConfig;

import java.util.List;

/**
 * Created by tanghc on 17/2/15.
 */
public class DubboTestBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    private Boolean checkPort = true;
    private String ipPre;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        try {
            String[] beanNamesForType = beanFactory.getBeanNamesForType(ProtocolConfig.class);
            if (null != beanNamesForType) {
                for (String name : beanNamesForType) {
                    ProtocolConfig bean = (ProtocolConfig) beanFactory.getBean(name);
                    String localIp = null;
                    if (StringUtils.isNotBlank(ipPre)) {
                        List<String> localIps = NetUtil.getLocalIps();
                        if (null != localIps) {
                            for (String ip : localIps) {
                                if (ip.indexOf(ipPre) != -1) {
                                    localIp = ip;
                                    break;
                                }
                            }
                        }
                    }
                    if (null == localIp) {
                        localIp = NetUtil.getIpCanConnect(30000, 100);
                    }
                    if (null != bean && StringUtils.isNotBlank(localIp)) {
                        bean.setHost(localIp);
                        if (checkPort) {
                            int availablePort = NetUtil.getAvailablePort(localIp, 20880);
                            bean.setPort(availablePort);
                        }
                    }
                }
            }

        } catch (Exception e) {
            logger.info("modify protocolconfig host fail: {}", e.getMessage());
        }
    }

    public Boolean getCheckPort() {
        return checkPort;
    }

    public void setCheckPort(Boolean checkPort) {
        this.checkPort = checkPort;
    }

    public String getIpPre() {
        return ipPre;
    }

    public void setIpPre(String ipPre) {
        this.ipPre = ipPre;
    }
}
